<template>
  <div style="margin-top:30px">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item  label="客户" prop="shipmentCode">
              <shipmentSelect ref="shipmentSelect"  @setCustomerCode="setCustomerCode" style="width: 100%"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="备注" prop="remarks" style="margin-right:15px">
              <el-input v-model="form.remarks" placeholder="请输入备注" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="合同名称" prop="name" style="margin-right:15px">
              <el-input v-model="form.name" placeholder="请输入合同名称" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="有效期" prop="validityDate" min-width="350"  style="margin-right:15px">
              <el-date-picker
                v-model="validityDate"
                value-format="yyyy-MM-dd"
                type="daterange"
                style="width:100%"
            range-separator="至"

                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="附件地址" prop="contractPath">
              <el-upload
                ref="upload"
                class="upload-demo"
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :auto-upload="true"
                :on-success="handleAvatarSuccess"
                :on-error="handleError"
                :before-upload="beforeUploadFile"
                :file-list="fileList"
                :headers="getAuthorization()"
              >
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              </el-upload>
              <el-input v-model="form.fileName" type="hidden" />
              <el-input v-model="form.contractPath" type="hidden" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="funcCancel">取 消</el-button>
      <el-button type="primary" @click="funcSubmit">确 定</el-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import request from '@/utils/request'
import shipmentSelect from '@/views/components/shipmentSelect.vue'

Vue.use(VXETable)
export default {
  name: 'ContractAdd',
  components:{
    shipmentSelect
  },
  data() {
    return {
      uploadUrl: this.BASE_API_URL + "ntocc-tps-api/fileUpload",
      uploadComplete:true,
      validityDate:'',
      form: {
        code: '',
        shipmentCode: '',
        shipmentName:'',
        name: '',
        remarks:'',
        contractPath: '',
        validityDate:'',
        startDate: '',
        endDate: ''
      },
      fileList:  [],
      rules: {
        code: [
          { required: true, message: '请输入预约入库单号', trigger: 'blur' },

        ],
        shipmentCode: [
          { required: true, message: '请输入客户姓名', trigger: 'change' },

        ],
        name: [
          { required: true, message: '请输入合同名称', trigger: 'blur' },

        ],
        contractPath: [
          { required: true, message: '请输入附件地址', trigger: 'blur' }
        ],
        validityDate: [
            { required: true, message: '请输入有效期', trigger: 'blur',
              validator: (rule, value, callback) =>{
                  if(this.validityDate==null||this.validityDate.length<2){
                      callback(new Error('请输入有效期'));
                  }else{
                      callback();
                  }


              }}
        ]
      }
    }
  },
  created() {
    // 保存空表单对象
    this.emptyForm = JSON.parse(JSON.stringify(this.form))
  },
  methods: {
    // 获取页面信息
    getInfo(code) {
      this.fileList = []
      // 查询到数据之前先展示空表单
      this.form = JSON.parse(JSON.stringify(this.emptyForm))
      request({ url: `/ntocc-wms-api/contract/${code}`, method: 'get' }).then(response => {
        // this.form.code = response.data.fileInfo.code
        this.form = response.data.entity
        this.$refs.shipmentSelect.setSelectValue(this.form.shipmentCode)
        // this.form.shipmentCode = this.formattershipment(response.data.entity.shipmentCode)
        this.fileList.push(response.data.fileInfo)
        this.$refs['form'].clearValidate();
        this.validityDate = [];
        if(this.form.startDate){
          this.validityDate[0] = this.form.startDate
          this.validityDate[1] = this.form.endDate
          this.form.validityDate = this.validityDate
        }
      })
    },
    //上传前校验
    beforeUploadFile(file) {
        let extension = file.name.substring(file.name.lastIndexOf('.')+1)
        let size = file.size / 1024 / 1024
        // if(extension !== 'xls') {
        //   this.$message.error("只能上传xls,xlsx的文件")
        // }
        if(size > 10) {
            this.$message.error('上传文件大小不能超过 10MB!')
            return false;
        }
        this.uploadComplete=false;

    },
    setCustomerCode(value) {
      this.form.shipmentCode = value;
      this.tableData = [];
      this.form.shipmentName = value.name
    },
    // 翻译客户类型
    formattershipment(cellValue) {
      const sd = this.partys.find(i => i.code === cellValue)
      return sd.name
    },
    handleRemove(file, fileList) {
        if(fileList.length<1){
            this.form.contractPath='';
        }
    },
    handlePreview(file) {
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
        this.uploadComplete=true
        this.$notify.error({
            title: '错误',
            message: `文件上传失败`
        });

    },
    handleAvatarSuccess(response, file, fileList) {
      this.$message({ message: response.msg, type: 'success' })
      this.form.contractPath = response.data
      this.form.fileName = file.name
      this.uploadComplete=true
      this.$refs['form'].validateField('contractPath');
    },

    // 提交
    funcSubmit() {
        if(!this.uploadComplete){
            this.$message({ message: '请先等待上传完成再提交', type: 'error' })
            return false;
        }
      this.form.validityDate = this.validityDate;
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.startDate = this.form.validityDate[0];
          this.form.endDate = this.form.validityDate[1];
          const data = this.form
          request({ url: '/ntocc-wms-api/contract', method: 'put', data }).then(response => {
            this.$message({ message: response.msg, type: 'success' })
            this.$emit('fatherEditMethod')
          })
        } else {
          return false
        }
      })
    },
    // 取消
    funcCancel() {
      this.$emit('fatherCancelMethod', 'edit')
    }

  }
}
</script>
<style lang="scss" scoped>
    .dialog-footer {
        margin:15px 0 15px 0;
        width: 175px;
        float: right;
    }
</style>
